
import TSMap from "../math/TSMap";
import BaseObject from "../base/BaseObject";
export default class EventDispatcher extends BaseObject {

        private eventMap : TSMap;
    
        constructor(){
            super();
            this.eventMap = new TSMap();
        }
    
        public addEventListener(eventName: any = "",callback: Function , target: Object){
            let list = this.eventMap.get(eventName);
            if(!list){
                list = [];
                this.eventMap.set(eventName,list);
                list.push({handler:callback,target:target});
            }else{
                if(!this.has(eventName,callback,target)){
                    list.push({handler:callback,target:target});
                }
            }
            if(list.length > 5 ){
                cc.warn(' EventDispatcher addEventListener  ',list.length,eventName )
            }
        }
     
        public has(eventName: any,callback,target): boolean{
            let list =  this.eventMap.get(eventName);
            if(list){
                if(list.length > 5 ){
                    cc.warn(' EventDispatcher has  ',list.length ,eventName)
                }
                for (let index = 0; index < list.length; index++) {
                    const element = list[index];
                    if(element.handler === callback && element.target === target){
                        return element;
                    }
                }
            }        
            return null;
        }
    
        public removeEventListener(eventName:any ,callback: Function,target: Object){
            let list:Array<any> =  this.eventMap.get(eventName);
            if(list){
                for (let index = 0; index < list.length; index++) {
                    const element = list[index];
                    if(element.handler === callback && element.target === target){
                        list.splice(index,1);
                        return;
                    }
                }
            }         
        }
    
        public publish(eventName: any,data?:any,data2?:any,data3?){
            let list =  this.eventMap.get(eventName);
            if(list){
                list.forEach(element => {
                    element.handler.call(element.target,data,data2,data3);
                });
            }
        }
    
        public removeAllEventListener(){
            this.eventMap.clear();
        }
    
        public removeEventListenerByName(eventName){
            this.eventMap.set(eventName,[]);
        }
    
}


